package de.toolschmied.jjas.client.widgets.toolbar;

import java.util.LinkedList;

import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.UIObject;

/**
 * A PopupToolbar is just a container for several toolbars which
 * can be shown and hidden.
 */
public class PopupToolbar {

	private final PopupPanel popup = new PopupPanel();
	private final HorizontalPanel panel = new HorizontalPanel();
	private final LinkedList<Toolbar> toolbars = new LinkedList<Toolbar>();
	
	public PopupToolbar() {
		popup.setWidget(panel);
	}
	
	public void addToolbar(Toolbar toolbar) {
		if (!toolbars.isEmpty()) {
			toolbar.showSeparator();
		}
		toolbars.add(toolbar);
		panel.add(toolbar);
	}
	
	public void showBelow(UIObject uiObject) {
		checkPosition(uiObject);
		checkSize();
		popup.show();
	}
	
	public void checkSize() {
		int height = 20;
		int width = 100;
		
		for (Toolbar toolbar : toolbars) {
			height = Math.max(height, toolbar.getOffsetHeight());
			width += toolbar.getOffsetWidth();
		}
		
		popup.setHeight(height + "px");
		popup.setWidth(width + "px");
	}
	
	public void checkPosition(UIObject uiObject) {
		int left = uiObject.getAbsoluteLeft();
		int top = uiObject.getAbsoluteTop() + uiObject.getOffsetHeight();
		popup.setPopupPosition(left, top);
	}
	
	public void hide() {
		popup.hide();
	}
	
}
